package org.kjtc.weChatUtil;

import com.google.zxing.BarcodeFormat;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kjtc.controller.MessageController;
import org.kjtc.entity.Template;
import org.kjtc.entity.WechatConfig;
import org.kjtc.service.WeChartService;
import org.springframework.data.redis.core.RedisTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
	protected static Logger logger = Logger.getLogger(CommonUtil.class);
	public final static String wechat_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public final static String wechat_createMenu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	public final static String wechat_deleteMenu_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	public final static String wechat_getMenu_url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	public final static String wechat_sendMessage_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	public final static String wechat_authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=BASEURL&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
	public final static String wechat_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	public final static String wechat_QrCode_url = "http://www.kejiatc.cn/WeChat/getAuthorizeBaseCode?url=http://www.kejiatc.cn/WeChat/toLogin";
	public final static String wechat_subscribeUser = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
	public final static String wechat_userInfo = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	public final static String wechat_usersInfo = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN";
	public final static String appid = "wx0e82324b8c475e52";
	public final static String appsecret = "88b28b0d9bb46f5476f35d597c50e939";
	public final static String baseUrl_iev365 = "http://www.iev365.com/WeChat/";
	public final static String baseUrl_kejiatc = "http://www.kejiatc.cn/WeChat/";
	public final static String SESSION_USER = "OpenID";
	public final static String SESSION_UUID = "Uuid";
	public final static String Redis_WeChat_AccessToken = "WeChatAccessToken";
	public final static int login_timeout = 120;
	public final static boolean test_model = false;
	public final static String MOBILE_LOCATION = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=MOBILE";

	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(requestMethod);

			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 从输入流读取返回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			System.out.printf("连接超时：{}", ce);
		} catch (Exception e) {
			System.out.printf("https请求异常：{}", e);
		}
		return jsonObject;
	}

	public static String getToken(String appid, String appsecret, RedisTemplate<String, Object> redisTemplate) {
		String token = null;
		if (redisTemplate != null && redisTemplate.hasKey(Redis_WeChat_AccessToken)) {
			token = (String)redisTemplate.opsForValue().get(Redis_WeChat_AccessToken);
			if (!StringUtils.isEmpty(token)) {
				return token;
			}
		} else {
			// 发起GET请求获取凭证
			JSONObject jsonObject = httpsRequest(wechat_token_url.replace("APPID", appid).replace("APPSECRET", appsecret), "GET", null);
			if (null != jsonObject) {
				try {
					if (jsonObject.has("errcode")) {
						logger.error("获取token失败：" + jsonObject.getInt("errcode") + "，" + jsonObject.getString("errmsg"));
					} else {
						if (jsonObject.has("access_token") && jsonObject.has("expires_in")) {
							token = jsonObject.getString("access_token");
							redisTemplate.opsForValue().set(Redis_WeChat_AccessToken, jsonObject.getString("access_token"), jsonObject.getInt("expires_in") - 60, TimeUnit.SECONDS);
						} else {
							logger.error("获取token信息错误：" + jsonObject.toString());
						}
					}
				} catch (JSONException e) {
					// 获取token失败
					logger.error("获取token异常：" + e.getMessage());
				}
			} else {
				logger.error("获取token失败：微信访问失败！");
			}
		}
		return token;
	}

	public static int createMenu(String menu, String accessToken) {
		int errorCode = 1;
		if (menu == null) {
			logger.error("创建自定义菜单信息不存在！" );
			return errorCode;
		} else if (accessToken == null) {
			logger.error("创建自定义菜单的accessToken不存在" );
			return errorCode;
		}
		// 拼装创建菜单的url
		String url = wechat_createMenu_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
        JSONObject jsonObject = httpsRequest(url, "POST", menu);
		if(jsonObject != null && jsonObject.has("errcode")){
			errorCode = jsonObject.getInt("errcode");
			if (errorCode != 0) {
				logger.error("创建自定义菜单微信接口失败：" + errorCode + "，" + jsonObject.getString("errmsg"));
			}
		} else {
			logger.error("创建自定义菜单微信接口失败：微信无结果返回" );
		}
		return errorCode;
    }

	public static int deleteMenu(String accessToken) {
		int errorCode = 1;
		if (accessToken == null) {
			logger.error("创建自定义菜单的accessToken不存在" );
			return errorCode;
		}
		// 拼装创建菜单的url
		String url = wechat_deleteMenu_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
        JSONObject jsonObject = httpsRequest(url, "Get", null);
		if(jsonObject != null && jsonObject.has("errcode")){
			errorCode = jsonObject.getInt("errcode");
			if (errorCode != 0) {
				logger.error("删除自定义菜单微信接口失败：" + errorCode + "，" + jsonObject.getString("errmsg"));
			}
		} else {
			logger.error("删除自定义菜单微信接口失败：微信无结果返回" );
		}
		return errorCode;
    }

	public static int sendMessage(String token, Template template){

		String requestUrl = wechat_sendMessage_url.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = httpsRequest(requestUrl, "POST", template.toJSON());
		int errorCode = 1;
		if(jsonObject != null && jsonObject.has("errcode")){
			errorCode = jsonObject.getInt("errcode");
			if (errorCode != 0) {
				logger.error("发送微信信息失败：" + errorCode + "，" + jsonObject.getString("errmsg"));
			} else {

			}
		} else {
			logger.error("发送微信信息失败：微信无结果返回" );
		}
		return errorCode;
	}

	public static String getErrorReason(int errorCode){
		String errorReason = null;
		switch(errorCode){
			case 1:
				errorReason = "微信无结果返回";
				break;
			case -1:
				errorReason = "系统繁忙，请稍后再试";
				break;
			case 0:
				errorReason = "请求成功";
				break;
			case 40001:
				//获取 access_token 时 AppSecret 错误，或者 access_token 无效。请开发者认真比对 AppSecret 的正确性，或查看是否正在为恰当的公众号调用接口
				errorReason = "验证失败，AppSecret错误或access_token无效";
				break;
			case 40002:
				errorReason = "不合法的凭证类型";
				break;
			case 40003:
				//确认 OpenID （该用户）是否已关注公众号，或是否是其他公众号的 OpenID
				errorReason = "不合法的OpenID";
				break;
			case 40004:
				errorReason = "不合法的媒体文件类型";
				break;
			case 40005:
				errorReason = "不合法的文件类型";
				break;
			case 40006:
				errorReason = "不合法的文件大小";
				break;
			case 40007:
				errorReason = "不合法的媒体文件id";
				break;
			case 40008:
				errorReason = "不合法的消息类型";
				break;
			case 40009:
				errorReason = "不合法的图片文件大小";
				break;
			case 40010:
				errorReason = "不合法的语音文件大小";
				break;
			case 40011:
				errorReason = "不合法的视频文件大小";
				break;
			case 40012:
				errorReason = "不合法的缩略图文件大小";
				break;
			case 40013:
				errorReason = "不合法的APPID";
				break;
			case 40014:
				// 认真比对 access_token 的有效性（如是否过期），或查看是否正在为恰当的公众号调用接口
				errorReason = "不合法的access_token";
				break;
			case 40015:
				errorReason = "不合法的菜单类型";
				break;
			case 40016:
				errorReason = "不合法的按钮个数";
				break;
			case 40017:
				errorReason = "不合法的按钮个数";
				break;
			case 40018:
				errorReason = "不合法的按钮名字长度";
				break;
			case 40019:
				errorReason = "不合法的按钮KEY长度";
				break;
			case 40020:
				errorReason = "不合法的按钮URL长度";
			case 40021:
				errorReason = "不合法的菜单版本号";
			case 40022:
				errorReason = "不合法的子菜单级数";
			case 40023:
				errorReason = "不合法的子菜单按钮个数";
			case 40024:
				errorReason = "不合法的子菜单按钮类型";
			case 40025:
				errorReason = "不合法的子菜单按钮名字长度";
				break;
			case 40026:
				errorReason = "不合法的子菜单按钮 KEY 长度";
				break;
			case 40027:
				errorReason = "不合法的子菜单按钮 URL 长度";
				break;
			case 40028:
				errorReason = "不合法的自定义菜单使用用户";
				break;
			case 40029:
				errorReason = "不合法的 oauth_code";
				break;
			case 40030:
				errorReason = "不合法的 refresh_token";
				break;
			case 40031:
				errorReason = "不合法的 openid 列表";
				break;
			case 40032:
				errorReason = "不合法的 openid 列表长度";
				break;
			case 40033:
				errorReason = "不合法的请求字符，不能包含 \\uxxxx 格式的字符";
				break;
			case 40035:
				errorReason = "不合法的参数";
				break;
			case 40038:
				errorReason = "不合法的请求格式";
				break;
			case 40039:
				errorReason = "不合法的 URL 长度";
				break;
			case 40050:
				errorReason = "不合法的分组 id";
				break;
			case 40051:
				errorReason = "分组名字不合法";
				break;
			case 40060:
				errorReason = "删除单篇图文时，指定的 article_idx 不合法";
				break;
			case 40117:
				errorReason = "分组名字不合法";
				break;
			case 40118:
				errorReason = "media_id 大小不合法";
				break;
			case 40119:
				errorReason = "button 类型错误";
				break;
			case 40120:
				errorReason = "button 类型错误";
				break;
			case 40121:
				errorReason = "不合法的 media_id 类型";
				break;
			case 40132:
				errorReason = "微信号不合法";
				break;
			case 40137:
				errorReason = "不支持的图片格式";
				break;
			case 40155:
				errorReason = "请勿添加其他公众号的主页链接";
				break;
			case 41001:
				errorReason = "缺少access_token参数";
				break;
			case 41002:
				errorReason = "缺少appid参数";
				break;
			case 41003:
				errorReason = "缺少refresh_token参数";
				break;
			case 41004:
				errorReason = "缺少secret参数";
				break;
			case 41005:
				errorReason = "缺少多媒体文件数据";
				break;
			case 41006:
				errorReason = "access_token超时";
				break;
			case 41007:
				errorReason = "缺少子菜单数据";
				break;
			case 41008:
				errorReason = "缺少 oauth code";
				break;
			case 41009:
				errorReason = "缺少 openid";
				break;
			case 42001:
				// access_token 超时，请检查 access_token 的有效期，请参考基础支持 - 获取 access_token 中，对 access_token 的详细机制说明
				errorReason = "access_token 超时，请检查 access_token 的有效期";
				break;
			case 42002:
				errorReason = "refresh_token 超时";
				break;
			case 42003:
				errorReason = "oauth_code 超时";
				break;
			case 42007:
				errorReason = "用户修改微信密码， accesstoken 和 refreshtoken 失效，需要重新授权";
				break;
			case 43001:
				errorReason = "需要GET请求";
				break;
			case 43002:
				errorReason = "需要POST请求";
				break;
			case 43003:
				errorReason = "需要HTTPS请求";
				break;
			case 43004:
				errorReason = "需要接收者关注";
				break;
			case 43005:
				errorReason = "需要好友关系";
				break;
			case 43019:
				errorReason = "需要将接收者从黑名单中移除";
				break;
			case 44001:
				errorReason = "多媒体文件为空";
				break;
			case 44002:
				errorReason = "POST的数据包为空";
				break;
			case 44003:
				errorReason = "图文消息内容为空";
				break;
			case 44004:
				errorReason = "文本消息内容为空";
				break;
			case 45001:
				errorReason = "多媒体文件大小超过限制";
				break;
			case 45002:
				errorReason = "消息内容超过限制";
				break;
			case 45003:
				errorReason = "标题字段超过限制";
				break;
			case 45004:
				errorReason = "描述字段超过限制";
				break;
			case 45005:
				errorReason = "链接字段超过限制";
				break;
			case 45006:
				errorReason = "图片链接字段超过限制";
				break;
			case 45007:
				errorReason = "语音播放时间超过限制";
				break;
			case 45008:
				errorReason = "图文消息超过限制";
				break;
			case 45009:
				errorReason = "接口调用超过限制";
				break;
			case 45010:
				errorReason = "创建菜单个数超过限制";
				break;
			case 45011:
				errorReason = "API调用太频繁，请稍候再试";
				break;
			case 45015:
				errorReason = "回复时间超过限制";
				break;
			case 45016:
				errorReason = "系统分组，不允许修改";
				break;
			case 45017:
				errorReason = "分组名字过长";
				break;
			case 45018:
				errorReason = "分组数量超过上限";
				break;
			case 45047:
				errorReason = "客服接口下行条数超过上限";
				break;
			case 46001:
				errorReason = "不存在媒体数据";
				break;
			case 46002:
				errorReason = "不存在的菜单版本";
				break;
			case 46003:
				errorReason = "不存在的菜单数据";
				break;
			case 46004:
				errorReason = "不存在的用户";
				break;
			case 47001:
				errorReason = "解析JSON/XML内容错误";
				break;
			case 48001:
				// api 功能未授权，请确认公众号已获得该接口，可以在公众平台官网 - 开发者中心页中查看接口权限
				errorReason = "api功能未授权，请确认公众号已获得该接口";
				break;
			case 48002:
				// 粉丝拒收消息（粉丝在公众号选项中，关闭了 “ 接收消息 ” ）
				errorReason = "粉丝拒收消息";
				break;
			case 48004:
				errorReason = "api接口被封禁，请登录mp.weixin.qq.com查看详情";
				break;
			case 48005:
				errorReason = "api禁止删除被自动回复和自定义菜单引用的素材";
				break;
			case 48006:
				errorReason = "api禁止清零调用次数，因为清零次数达到上限";
				break;
			case 48008:
				errorReason = "没有该类型消息的发送权限";
				break;
			case 50001:
				errorReason = "用户未授权该api";
				break;
			case 50002:
				errorReason = "用户受限，可能是违规后接口被封禁";
				break;
			case 61451:
				errorReason = "参数错误 (invalid parameter)";
				break;
			case 61452:
				errorReason = "无效客服账号 (invalid kf_account)";
				break;
			case 61453:
				errorReason = "客服帐号已存在 (kf_account exsited)";
				break;
			case 61454:
				errorReason = "客服帐号名长度超过限制 ( 仅允许 10 个英文字符，不包括 @ 及 @ 后的公众号的微信号 )(invalid kf_acount length)";
				break;
			case 61455:
				errorReason = "客服帐号名包含非法字符 ( 仅允许英文 + 数字 )(illegal character in kf_account)";
				break;
			case 61456:
				errorReason = "客服帐号个数超过限制 (10 个客服账号 )(kf_account count exceeded)";
				break;
			case 61457:
				errorReason = "无效头像文件类型 (invalid file type)";
				break;
			case 61450:
				errorReason = "系统错误 (system error)";
				break;
			case 61500:
				errorReason = "日期格式错误";
				break;
			case 65301:
				errorReason = "不存在此 menuid 对应的个性化菜单";
				break;
			case 65302:
				errorReason = "没有相应的用户";
				break;
			case 65303:
				errorReason = "没有默认菜单，不能创建个性化菜单";
				break;
			case 65304:
				errorReason = "MatchRule 信息为空";
				break;
			case 65305:
				errorReason = "个性化菜单数量受限";
				break;
			case 65306:
				errorReason = "不支持个性化菜单的帐号";
				break;
			case 65307:
				errorReason = "个性化菜单信息为空";
				break;
			case 65308:
				errorReason = "包含没有响应类型的 button";
				break;
			case 65309:
				errorReason = "个性化菜单开关处于关闭状态";
				break;
			case 65310:
				errorReason = "填写了省份或城市信息，国家信息不能为空";
				break;
			case 65311:
				errorReason = "填写了城市信息，省份信息不能为空";
				break;
			case 65312:
				errorReason = "不合法的国家信息";
				break;
			case 65313:
				errorReason = "不合法的省份信息";
				break;
			case 65314:
				errorReason = "不合法的城市信息";
				break;
			case 65316:
				errorReason = "该公众号的菜单设置了过多的域名外跳（最多跳转到 3 个域名的链接）";
				break;
			case 65317:
				errorReason = "不合法的 URL";
				break;
			default:
				errorReason = "不明错误原因：" + errorCode;
				break;
		}
		return errorReason;
	}
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String token = "kjtc2017";
		String [] array = {token, timestamp, nonce};
		if (token != null && timestamp != null && nonce!= null) {
			Arrays.sort(array);
		}
		String my_signature = DigestUtils.sha1Hex(StringUtils.join(array));
		return my_signature.equals(signature);
	}

	public static Date str2DateTime(String date){
		if (date != null) {
			if(date.length() == 10) {
				date = date + " 00:00:00";
			} else if(date.length() == 13) {
				date = date + ":00:00";
			} else if (date.length() == 16) {
				date = date + ":00";
			} else {
				return null;
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return null;
		} else {
			return null;
		}
	}

	public static String date2Str(Date date, String format){
		if(date != null){
			if (format == null) {
				format = "yyyy-MM-dd HH:mm:ss";
			}
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}else{
			return "";
		}
	}

	public static Date strTimes2Date(long times){
		if (times > 0) {
			Date date = new Date();
			date.setTime(times);
			return date;
		} else {
			return null;
		}
	}

	public static String strTimes2StrDate(long times, String format){
		if (times > 0) {
			Date date = new Date();
			date.setTime(times);
			return date2Str(date, format);
		} else {
			return "";
		}
	}

	public static BufferedImage createWeChatQRCode(String url, Integer width, Integer height, Object errorCorrectionLevel) throws Exception{
		if (width == null) {
			width = 240;
		}
		if (height == null) {
			height = 240;
		}
		ZXingCode zp = ZXingCode.getInstance();
		BufferedImage image = zp.getQRCODEBufferedImage(url, BarcodeFormat.QR_CODE, width, height, zp.getDecodeHintType(errorCorrectionLevel));
		return image;
	}

	public static String getSNCode(){
		return String.valueOf(System.currentTimeMillis()) ;
	}

	public static String getRandom() {
		Random r = new Random();
		String sn1 = r.nextInt(8999) + 1000 + "";
		String sn2 = r.nextInt(8999) + 1000 + "";
		String sn3 = r.nextInt(8999) + 1000 + "";
		String sn = sn1 + "-" + sn2 + "-" + sn3;
		return sn;
	}

	public static boolean isNumeric(String str){
		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher isNum = pattern.matcher(str);
		if(!isNum.matches()){
			return false;
		}
		return true;
	}
	public static Long getEveryDayDiff(String time){
		if (time != null && !time.isEmpty() && time.length() <= 8) {
			if (time.length() == 2) {
				time += ":00:00";
			} else if (time.indexOf(":") >= 0 && time.length() == 5) {
				time += ":00";
			} else if (time.indexOf(":") >= 0 && time.length() == 8) {

			} else {
				return null;
			}
			Date now = new Date();
			time = date2Str(now, "yyyy-MM-dd") + " " + time;
			return now.getTime() - str2DateTime(time).getTime();
		} else {
			return null;
		}
	}

	public static Object sendWechatMessage(String type, List<String> keywordlist, WeChartService weChartService, RedisTemplate<String, Object> redisTemplate){

		if (!StringUtils.isEmpty(type)) {
			WechatConfig wechatConfig = new WechatConfig();
			wechatConfig.setType(type);
			List<WechatConfig> wechatConfigList = weChartService.getWechatConfig(wechatConfig);
			if (wechatConfigList.size() > 0) {
				wechatConfig = wechatConfigList.get(0);
				Long StartSendTime = getEveryDayDiff(wechatConfig.getStartSendTime());
				Long EndSendTime = getEveryDayDiff(wechatConfig.getEndSendTime());
				if ((StartSendTime == null || (StartSendTime != null && StartSendTime >= 0)) && (EndSendTime == null || (EndSendTime != null && EndSendTime < 0))) {
					JSONObject json = new JSONObject();
					json.put("type", type);
					json.put("sendFrom", "微信平台");
					json.put("templateID", wechatConfig.getTemplateID());
					if (!StringUtils.isEmpty(wechatConfig.getUrl())) {
						json.put("url", wechatConfig.getUrl());
					}
					json.put("userID", wechatConfig.getSendUserID());
					json.put("appid", wechatConfig.getAppid());
					json.put("pagepath", wechatConfig.getPagepath());
					JSONObject messageJson = new JSONObject();
					if (wechatConfig.getFirstColor() != null && !wechatConfig.getFirstColor().isEmpty()) {
						messageJson.put("first", "{value: \"" + wechatConfig.getFirst() + "\", color: \"" + wechatConfig.getFirstColor() + "\"}");
					} else {
						messageJson.put("first", "{value: \"" + wechatConfig.getFirst() + "\"}");
					}
					int length = keywordlist.size();
					if (length > 0) {
						String value = null;
						String [] keywordColorList = null;
						if (wechatConfig.getKeywordColor() != null && !wechatConfig.getKeywordColor().isEmpty()) {
							keywordColorList = wechatConfig.getKeywordColor().split(",");
						}
						int colorLength = 0;
						if (keywordColorList != null) {
							colorLength = keywordColorList.length;
						}
						for (int i = 0; i < length; i++) {
							if ("date".equals(keywordlist.get(i))) {
								value = date2Str(new Date(), null);
							} else if ("sendFrom".equals(keywordlist.get(i))) {
								value = wechatConfig.getSendFrom();
							} else {
								value = keywordlist.get(i);
							}
							messageJson.put("keyword" + (i + 1), "{value: \"" + value + "\"}");
							if (colorLength > 0 && colorLength >= i) {
								messageJson.put("keyword" + (i + 1), "{value: \"" + value + "\", color: \"" + keywordColorList[i] + "\"}");
							}

						}
					}
					if (wechatConfig.getRemarkColor() != null && !wechatConfig.getRemarkColor().isEmpty()) {
						messageJson.put("remark", "{value: \"" + wechatConfig.getRemark() + "\", color: \"" + wechatConfig.getRemarkColor() + "\"}");
					} else {
						messageJson.put("remark", "{value: \"" + wechatConfig.getRemark() + "\"}");
					}
					json.put("data", messageJson);
					MessageController messageController = new MessageController();
					Object result = messageController.sendWeChatMessage(null, json.toString(), weChartService, redisTemplate);
					messageJson = null;
					json = null;
					messageController = null;
					return result;
				} else {
					logger.warn("微信消息发送失败：不在发送时间内");
				}
				StartSendTime = null;
				EndSendTime = null;
			} else {
				logger.error("微信消息发送失败：消息type【" + type + "】不存在");
			}
		} else {
			logger.error("微信消息发送失败：消息type为空");
		}
		return null;
	}

	public static JSONObject getWechatUserInfo(String token, String openid, String requestMethod){
		String requestUrl = null;
		if ("POST".equals(requestMethod)) {
			requestUrl = wechat_usersInfo.replace("ACCESS_TOKEN", token);
		} else {
			requestUrl = wechat_userInfo.replace("ACCESS_TOKEN", token).replace("OPENID", openid);
		}
		JSONObject jsonObject = httpsRequest(requestUrl, (StringUtils.isEmpty(requestMethod) ? "GET" : requestMethod), openid);
		if(jsonObject != null){
			if (jsonObject.has("errcode")){
				int errorCode = jsonObject.getInt("errcode");
				logger.error("获取微信用户信息失败：" + errorCode + "，" + jsonObject.getString("errmsg"));
				jsonObject = null;
			}
		} else {
			logger.error("获取微信用户信息失败：微信无结果返回" );
		}
		return jsonObject;
	}

	public static JSONArray pullSubscribeUser(String token, String next_openid, JSONArray openid){

		String requestUrl = wechat_subscribeUser.replace("ACCESS_TOKEN", token);
		if (next_openid == null) {
			next_openid = "";
		}
		requestUrl = requestUrl.replace("NEXT_OPENID", next_openid);
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		if(jsonObject != null){
			if (jsonObject.has("errcode")){
				int errorCode = jsonObject.getInt("errcode");
				logger.error("获取微信关注者列表失败：" + errorCode + "，" + jsonObject.getString("errmsg"));
				openid = null;
			} else {
				int total = 0;
				if (jsonObject.has("total")) {
					total = jsonObject.getInt("total");
				}
				int count = 0;
				if (jsonObject.has("count")) {
					count = jsonObject.getInt("count");
				}
				if (jsonObject.has("data")) {
					JSONObject jsonData = JSONObject.fromObject(jsonObject.getString("data"));
					if (jsonData.has("openid")) {
						if (openid == null) {
							openid = new JSONArray();
						}
						openid.addAll(JSONArray.fromObject(jsonData.getString("openid")));
					}
				}
				if (count == 10000 && count < total) {
					if (jsonObject.has("next_openid")) {
						pullSubscribeUser(token, jsonObject.getString("next_openid"), openid);
					}
				}
			}
		} else {
			openid = null;
			logger.error("获取微信关注者列表失败：微信无结果返回" );
		}
		return openid;
	}
    public static String checkUUID(String uuid) {
        if (!StringUtils.isEmpty(uuid)) {
            String time = uuid.split("_")[0];
            if (CommonUtil.isNumeric(time) && Long.parseLong(time) <= System.currentTimeMillis()) {
                if (System.currentTimeMillis() - Long.parseLong(time) > CommonUtil.login_timeout * 1000) {
                    return "Timeout";
                } else {
					return "Success";
				}
            } else {
                return "UuidError";
            }
        }
        return "";
    }
	public static JSONObject mobileLocation(String mobile) {

		JSONObject mobileJson = HttpJsonClient.get(MOBILE_LOCATION.replace("MOBILE", mobile));
		if (mobileJson.containsKey("body")) {
			String body = mobileJson.getString("body");
			if (body.indexOf("__GetZoneResult_") >= 0 && body.indexOf("{") >= 0) {
				mobileJson = JSONObject.fromObject(body.substring(body.indexOf("{")));
			}
		}
		return mobileJson;
	}
}
